<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="通知类型" prop="formData.field101">
        <el-select v-model="queryParams.formData.field101" placeholder="请选择下拉选择" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in queryParams.field101Options" :key="index" :label="item.tzlxName"
                     :value="item.tzlxId" :disabled="item.disabled"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="通知标题" prop="pttzTzbt">
        <el-input
          v-model="queryParams.pttzTzbt"
          placeholder="请输入通知标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户端" prop="formData1.field101">
        <el-select v-model="queryParams.formData1.field101" placeholder="请选择下拉选择" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in queryParams.field101Options1" :key="index" :label="item.khdName"
                     :value="item.khdId" :disabled="item.disabled"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="formData2.field101">
        <el-select v-model="queryParams.formData2.field101" placeholder="请选择下拉选择" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in queryParams.field101Options2" :key="index" :label="item.ztName"
                     :value="item.ztId" :disabled="item.disabled"></el-option>
        </el-select>
      </el-form-item>

<!--      <el-form-item label="创建时间">-->
<!--        <el-date-picker-->
<!--          v-model="daterangePttzCjsj"-->
<!--          style="width: 240px"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          type="daterange"-->
<!--          range-separator="-"-->
<!--          start-placeholder="开始日期"-->
<!--          end-placeholder="结束日期"-->
<!--        ></el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="发布时间">-->
<!--        <el-date-picker-->
<!--          v-model="daterangePttzFbsj"-->
<!--          style="width: 240px"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          type="daterange"-->
<!--          range-separator="-"-->
<!--          start-placeholder="开始日期"-->
<!--          end-placeholder="结束日期"-->
<!--        ></el-date-picker>-->
<!--      </el-form-item>-->

      <div class="block" style="float: left">
        <span class="demonstration">创建时间</span>
        <el-date-picker
          v-model="value1"
          type="datetimerange"
          :picker-options="pickerOptions1"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right">
        </el-date-picker>
      </div>

      <div class="block" style="float: left;margin-left: 125px">
        <span class="demonstration">发布时间</span>
        <el-date-picker
          v-model="value2"
          type="datetimerange"
          :picker-options="pickerOptions2"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right">
        </el-date-picker>
      </div>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:pingtaitongzhi:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:pingtaitongzhi:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:pingtaitongzhi:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:pingtaitongzhi:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pingtaitongzhiList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="pttzId" />
      <el-table-column label="通知类型" align="center" prop="tongzhileixing.tzlxName" />
      <el-table-column label="通知标题" align="center" prop="pttzTzbt" />
<!--      <el-table-column label="通知内容" align="center" prop="pttzTznr" />-->
<!--      <el-table-column label="通知链接" align="center" prop="pttzTzlj" />-->
      <el-table-column label="客户端" align="center" prop="kehuduan.khdName" />
      <el-table-column label="发布时间" align="center" prop="pttzFbsj" width="180">
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.pttzFbsj, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="pttzCjsj" width="180">
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.pttzCjsj, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="状态" align="center" prop="zhuangtai.ztName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:pingtaitongzhi:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:pingtaitongzhi:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改平台通知对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
<!--        <el-form-item label="通知类型id" prop="tzlxId">-->
<!--          <el-input v-model="form.tzlxId" placeholder="请输入通知类型id" />-->
<!--        </el-form-item>-->
        <el-form-item label="通知类型" prop="field">
          <el-select v-model="form.tzlxId" placeholder="请选择下拉选择" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in queryParams.field101Options" :key="index" :label="item.tzlxName"
                       :value="item.tzlxId" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="通知标题" prop="pttzTzbt">
          <el-input v-model="form.pttzTzbt" placeholder="请输入通知标题" />
        </el-form-item>
        <el-form-item label="通知内容" prop="pttzTznr">
          <el-input v-model="form.pttzTznr" placeholder="请输入通知内容" />
        </el-form-item>
        <el-form-item label="通知链接" prop="pttzTzlj">
          <el-input v-model="form.pttzTzlj" placeholder="请输入通知链接" />
        </el-form-item>
<!--        <el-form-item label="客户端id" prop="khdId">-->
<!--          <el-input v-model="form.khdId" placeholder="请输入客户端id" />-->
<!--        </el-form-item>-->
        <el-form-item label="客户端" prop="field1">
          <el-select v-model="form.khdId" placeholder="请选择下拉选择" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in queryParams.field101Options1" :key="index" :label="item.khdName"
                       :value="item.khdId" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="发布时间" prop="pttzFbsj">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.pttzFbsj"-->
<!--            type="date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            placeholder="请选择发布时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="创建时间" prop="pttzCjsj">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.pttzCjsj"-->
<!--            type="date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            placeholder="请选择创建时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--&lt;!&ndash;        <el-form-item label="状态id" prop="ztId">&ndash;&gt;-->
<!--&lt;!&ndash;          <el-input v-model="form.ztId" placeholder="请输入状态id" />&ndash;&gt;-->
<!--&lt;!&ndash;        </el-form-item>&ndash;&gt;-->
<!--        <el-form-item label="状态" prop="field2">-->
<!--          <el-select v-model="form.field2" placeholder="请选择下拉选择" clearable :style="{width: '100%'}">-->
<!--            <el-option v-for="(item, index) in queryParams.field101Options2" :key="index" :label="item.ztName"-->
<!--                       :value="item.ztId" :disabled="item.disabled"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">立即推送</el-button>
        <el-button type="primary" @click="dingshituisong">定时推送</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title1" :visible.sync="open1" width="500px" append-to-body>
      <div class="block">
        <span class="demonstration">选择定时点</span>
        <el-date-picker
          v-model="value3"
          type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </div>
      <el-button type="primary" @click="quedingdingshituisong">定 时 推 送</el-button>
    </el-dialog>
  </div>
</template>

<script>
import { listPingtaitongzhi, getPingtaitongzhi, delPingtaitongzhi, addPingtaitongzhi, updatePingtaitongzhi ,listTongzhileixing ,listKehuduan ,listZhuangtai} from "@/api/system/pingtaitongzhi";

export default {
  name: "Pingtaitongzhi",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 平台通知表格数据
      pingtaitongzhiList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title1: "",
      // 是否显示弹出层
      open1: false,
      //创建时间
      value1: '',
      //发布时间
      value2: '',
      //定时发布时间
      value3: '',

      // 查询参数
      queryParams: {
        //平台通知的查询参数
        pageNum: 1,
        pageSize: 10,
        tzlxId: null,
        pttzTzbt: null,
        pttzTznr: null,
        pttzTzlj: null,
        khdId: null,
        pttzFbsj: null,
        pttzCjsj: null,
        ztId: null,

        //通知类型的查询参数
        formData: {
          field101: undefined,
        },
        rules: {
          field101: [{
            required: true,
            message: '请选择下拉选择',
            trigger: 'change'
          }],
        },
        field101Options: [],

        //客户端的查询参数
        formData1: {
          field101: undefined,
        },
        rules1: {
          field101: [{
            required: true,
            message: '请选择下拉选择',
            trigger: 'change'
          }],
        },
        field101Options1: [],

        //状态的查询参数
        formData2: {
          field101: undefined,
        },
        rules2: {
          field101: [{
            required: true,
            message: '请选择下拉选择',
            trigger: 'change'
          }],
        },
        field101Options2: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      //状态
      zt_dfb:-1,
      zt_yfb:-1,
      zt_yty:-1,
      pickerOptions1: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      pickerOptions2: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    };
  },
  created() {
    this.getTzlxList();
    this.getKhdList();
    this.getZtList();
    this.getList();
  },
  methods: {
    /** 查询平台通知列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};

      if (null != this.value1 && '' != this.value1) {
        var a = this.getGoodTime(this.value1[0])
        var b = this.getGoodTime(this.value1[1])
        this.queryParams.params["beginPttzCjsj"] = a;
        this.queryParams.params["endPttzCjsj"] = b;
      }
      if (null != this.value2 && '' != this.value2) {
        var c = this.getGoodTime(this.value2[0])
        var d = this.getGoodTime(this.value2[1])
        this.queryParams.params["beginPttzFbsj"] = c;
        this.queryParams.params["endPttzFbsj"] = d;
      }
      this.queryParams.tzlxId = this.queryParams.formData.field101;
      this.queryParams.khdId = this.queryParams.formData1.field101;
      this.queryParams.ztId = this.queryParams.formData2.field101;
      listPingtaitongzhi(this.queryParams).then(response => {
        this.pingtaitongzhiList = response.rows;
        this.total = response.total;
        this.loading = false;
        for (let i = 0; i < response.rows.length; i++) {
          if((response.rows[i].pttzFbsj < this.getGoodTime(new Date())) && response.rows[i].ztId == this.zt_dfb){
            this.form = response.rows[i];
            this.form.ztId = this.zt_yfb
            updatePingtaitongzhi(this.form).then(response => {
              this.getList();
            });
          }
        }
      });
    },
    /** 查询通知类型 */
    getTzlxList(){
      listTongzhileixing().then(response => {
        this.queryParams.field101Options = response.rows;
      });
    },
    /** 查询客户端 */
    getKhdList(){
      listKehuduan().then(response => {
        this.queryParams.field101Options1 = response.rows;
      });
    },
    /** 查询状态 */
    getZtList(){
      listZhuangtai().then(response => {
        this.queryParams.field101Options2 = response.rows.slice(0,3);
        for (let i = 0; i < response.rows.length; i++) {
          if (response.rows[i].ztName == "待发布"){
            this.zt_dfb = i + 1;
          }else if (response.rows[i].ztName == "已发布"){
            this.zt_yfb = i + 1;
          }else if (response.rows[i].ztName == "已停用"){
            this.zt_yty = i + 1;
          }
        }
      });
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        pttzId: null,
        tzlxId: null,
        pttzTzbt: null,
        pttzTznr: null,
        pttzTzlj: null,
        khdId: null,
        pttzFbsj: null,
        pttzCjsj: null,
        ztId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.value1 = '';
      this.value2 = '';
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.pttzId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加平台通知";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const pttzId = row.pttzId || this.ids
      getPingtaitongzhi(pttzId).then(response => {
        this.form = response.data;
        this.form.field = response.data.tzlxId;
        this.form.field1 = response.data.khdId;
        this.open = true;
        this.title = "修改平台通知";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.ztId = this.zt_yfb;
          this.form.pttzFbsj = this.getGoodTime(new Date())
          if (this.form.pttzId != null) {
            updatePingtaitongzhi(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.pttzCjsj = this.getGoodTime(new Date())
            addPingtaitongzhi(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    dingshituisong(){
      this.value3 = "";
      this.open1 = true;
      this.title1 = "选择发布时间";
    },
    quedingdingshituisong(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.ztId = this.zt_dfb;
          if(this.value3 <= new Date()){
            alert("错误")
            return 0 ;
          }
          this.form.pttzFbsj = this.getGoodTime(this.value3)
          if (this.form.pttzId != null) {
            updatePingtaitongzhi(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.open1 = false;
              this.getList();
            });
          } else {
            this.form.pttzCjsj = this.getGoodTime(new Date())
            addPingtaitongzhi(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.open1 = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const pttzIds = row.pttzId || this.ids;
      this.$modal.confirm('是否确认删除平台通知编号为"' + pttzIds + '"的数据项？').then(function() {
        return delPingtaitongzhi(pttzIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

/** 导出按钮操作 */
    handleExport() {
      this.download('system/pingtaitongzhi/export', {
        ...this.queryParams
      }, `pingtaitongzhi_${new Date().getTime()}.xlsx`)
    },


    //时间格式转化
    getGoodTime(time) {
      // 尝试将输入字符串解析为Date对象
      let date = new Date(time);
      // 检查Date对象是否有效（即不是Invalid Date）
      if (isNaN(date.getTime())) {
        throw new Error('Invalid date string');
      }
    // 提取年、月、日、时、分、秒
    // 月份从0开始，所以要加1；日期、小时、分钟、秒直接使用
    // 使用padStart来确保月份、日期、小时、分钟、秒始终是两位数
    const year = time.getFullYear();
    const month = String(time.getMonth() + 1).padStart(2, '0');
    const day = String(time.getDate()).padStart(2, '0');
    const hours = String(time.getHours()).padStart(2, '0');
    const minutes = String(time.getMinutes()).padStart(2, '0');
    const seconds = String(time.getSeconds()).padStart(2, '0');

    // 拼接成所需的格式
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }

}
};
</script>
